package de.se.ludoapp.activity.task;

import android.content.Intent;
import android.os.AsyncTask;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.activity.GameActivity;
import de.se.ludoapp.activity.VisitorTableActivity;
import de.se.ludoapp.gaming.Game;
import de.se.ludoapp.response.GameResponse;

/**
 * Task get a game from server.
 * 
 * @author Marlen Rotert
 * 
 */
public class GetGameTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private VisitorTableActivity context;
	private int gameId;

	public GetGameTask(LudoApplication ludoApp, VisitorTableActivity context,
			int gameId) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		this.gameId = gameId;
	}

	/**
	 * accept user sent on server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute allowUserToEnterTheGame */
		GameResponse gameResponse = ludoApp.getLudoStub().getGameById(
				this.gameId);
		if (gameResponse.getReturnCode() == 0) {
			Game game = gameResponse.getGame();
			ludoApp.setCurrentGame(game);
		}
		return gameResponse.getMsg();
	}

	/**
	 * update gameinfos in view. <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		Game game = ludoApp.getCurrentGame();
		if (game != null) {
			Intent intentGame = new Intent(context, GameActivity.class);
			context.startActivity(intentGame);
			context.finish();
		}
	}
}
